from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest, HttpRequest
import simplejson
from .models import User
import logging
from django.conf import settings
from django.db.models.query import QuerySet
import bcrypt
import jwt
import datetime


AUTH_EXPIRE = 60 * 60 * 8


def checkemail(request):

    # 判断email
    return HttpResponse()

def gen_token(user_id):
    '''生成token'''
    tmp = {# 增加时间戳，判断是否重发tocken或者重新登陆
        'user_id': user_id,
        'timestamp': int(datetime.datetime.now().timestamp()) # 要取整
        }
    return jwt.encode(tmp, settings.SECRET_KEY, 'HS256').decode() # 字符串

def authenticate(view):

    def wrapper(request: HttpRequest):

        token = request.META.get("HTTP_JWT")
        # print(request.META)
        # print('token:',token)
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
            print(payload)
            print(payload['timestamp'])

            if (datetime.datetime.now().timestamp() - payload['timestamp'] > AUTH_EXPIRE):
                print("超时")
                return HttpResponse(status=401)

            user_id = payload['user_id']
            print(user_id)

            # user = User.objects.filter(id=user_id).get()
            user = User.objects.get(pk=user_id)
            print('user:', user.name)
            print(request)

            request.user = user
            print(1, request.user.name)

            # print(user)


        except Exception as e:
            print(e)
            return HttpResponse(status=401)

        return view(request)
    return wrapper

def test(request:HttpRequest):
    print(request.META.keys())
    return HttpResponse(b"hello world")

def reg(request:HttpRequest):
    try:
        payload=simplejson.loads(request.body)
        email = payload['email']
        print(email)
        query = User.objects.filter(email=email)
        if query:
            return HttpResponseBadRequest()

        name = payload['name']
        password = payload['password']

        print(email, name, password)
        user = User()
        user.email = email
        user.name = name
        print(type(payload['password']))
        user.password = bcrypt.hashpw(payload['password'].encode(), bcrypt.gensalt())


        print(user.email, user.name, user.password)

        try:
            user.save()
            return JsonResponse({'token': gen_token(user.id)})
        except:
            raise
    except Exception as e:
        print(e)
        return HttpResponseBadRequest()

def login(request:HttpRequest):
    try:
        payload = simplejson.loads(request.body)
        email = payload["email"]
        user = User.objects.filter(email=email).get()
        print(1,user.password)
        print(payload['password'])

        if bcrypt.checkpw(payload["password"].encode(), user.password.encode()):
            token = gen_token(user.id)
            print(token)
            res = JsonResponse({
                'user':{
                    'user_id': user.id,
                    'name': user.name,
                    'email' :user.email
                },
                'token': token
            })
            res.set_cookie('Jwt', token)
            return res
        else:
            return HttpResponseBadRequest()
    except Exception as e:
        print(e)
        return HttpResponseBadRequest()







